package com.blog.Interceptor;

import com.blog.common.prop.JwtProp;
import com.blog.common.thread.BaseThread;
import com.blog.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtIntercept implements HandlerInterceptor {
    @Autowired

    private JwtProp jwtProp;

    /**
     * preHandle
     * - 返回 true 代表放行
     * - 返回 false 代表拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        //  非OPTIONS请求进行拦截
        if (!method.equals("OPTIONS")) {
            String jwt = request.getHeader("Authorization");
            if (jwt == null || jwt.isEmpty()) {
                response.setStatus(401);
                throw new RuntimeException("请先登录");
            }
            System.out.println("jwt:" + jwtProp);
            try {
                Claims claims = JwtUtil.parseJWT(jwtProp.getSecretKey(), jwt);
                String userId = claims.get("userId", String.class);
                BaseThread.setId(userId);
            } catch (Exception e) {
                response.setStatus(401);
                System.out.println(e);
                throw new RuntimeException("令牌解析错误");
            }
        }
        return true;
    }
}